
'Copyright 2010 Brian L. Crawford

'Licensed under the Apache License, Version 2.0 (the "License");
'you may not use this file except in compliance with the License.
'You may obtain a copy of the License at

'    http://www.apache.org/licenses/LICENSE-2.0

'Unless required by applicable law or agreed to in writing, software
'distributed under the License is distributed on an "AS IS" BASIS,
'WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
'See the License for the specific language governing permissions and
'limitations under the License.

'This software uses Microsoft .Net framework used with permission from      
'Microsoft. Microsoft, .Net Framework, Visual Studio, Visual Basic, Visual C++ 
'remain the trademark and copyright of Microsoft and are subject to their 
'individual licenses.

Imports System.Collections.ObjectModel
Imports System.IO
Imports System.ComponentModel
Imports System.Windows.Forms
Imports System.IO.Directory

Public Module RENAMER

    Function fnRenameList(ByVal listboxDWF As ListBox, _
                          ByRef intStorenum As String, _
                          ByRef strExamplerename As String, _
                          ByRef strDefaultRemove As String) As ListBox
        'this is to change the name in the listbox
        Dim intStringStart As Integer
        'iterate collection
        For Each itemDWF As classListboxObject In listboxDWF.Items
            ' this line good only for listbox collections
            Dim strDisplay As String = itemDWF.DisplayName
            intStringStart = Strings.InStr(strDisplay, strDefaultRemove)
            'remove '-model'  perform check becuase 'model' could be anywhere in the filename or not at all.
            'we always want to get rid of the 'model' 
            If intStringStart <> 0 Then
                strDisplay = fnStringRemove(strDisplay, intStringStart, Len(strDefaultRemove))
            End If
            'check if intStorenum has a value.
            If intStorenum <> Nothing Then
                If Strings.InStr(strDisplay, intStorenum) > 0 Then
                    intStringStart = Strings.InStr(strDisplay, strDefaultRemove)
                    'if it does then replace the proto # or current store #
                    strDisplay = STRIP_CLUB_PROTO(strDisplay, intStorenum)
                End If
            End If
            itemDWF.UpdateDisplayName(strDisplay)

            'try to imitate the string in strExamplerename.  this is the case where someone wants to 
            'be different.
        Next

        Return listboxDWF
    End Function


    Public Function fnRenameList2(ByRef List1 As ListBox, _
                          ByRef intStorenum As String, _
                          ByRef strExamplerename As String, _
                          ByRef strDefaultRemove As String, _
                          Optional ByVal IsChecked As Boolean = False)


        Dim arrtemp As Object = Nothing
        Dim itemTemp As Object = Nothing
        Dim counter As Integer = 0
        Dim TextList As String = "Badly named files:" & Chr(13)
        Dim intStringStart As Integer
        Dim strDisplay As String
        For Each item In List1.Items
            'if you remove items for the collection while in this loop the enumerator will throw an 
            'exception becuase the scope will have changed and it doesn't have a way to deal with
            'dynamic collections

            If TypeOf item Is classListboxObject = False Then item = CType(item, classListboxObject)

            strDisplay = item.DisplayName
            intStringStart = Strings.InStr(strDisplay, strDefaultRemove)

            If intStringStart <> 0 Then
                strDisplay = fnStringRemove(strDisplay, intStringStart, Len(strDefaultRemove))
            End If
            'check if intStorenum has a value.
            If intStorenum <> Nothing Then
                If Strings.InStr(strDisplay, intStorenum) > 0 Then
                    intStringStart = Strings.InStr(strDisplay, strDefaultRemove)
                    'if it does then replace the proto # or current store #
                    strDisplay = STRIP_CLUB_PROTO(strDisplay, intStorenum)
                End If
            End If
            item.UpdateDisplayName(strDisplay)
            If IsChecked = True Then
                If Strings.InStr(item.DisplayName, StrEDDSfilenameparser(item.DisplayName), CompareMethod.Text) > 0 Then
                    counter += 1
                Else
                    TextList = TextList & Chr(13) & _
                                item.DisplayName
                End If
            End If
        Next

        Return TextList
    End Function

    Sub fnRenameFile(ByVal MyFileName As classListboxObject)
        'this is to change the name on the filesystem

        Dim MyFileObject As FileInfo = MyFileName.ListboxObject()
        Dim MyFileNameString As String = MyFileName.DisplayName()
        Dim sourcePath As String = MyFileObject.DirectoryName()
        Dim originalName As String = MyFileObject.Name()
        Dim newPathName As String = sourcePath & "\" & MyFileNameString
        If CheckIfFileExists(newPathName) = False Then MyFileObject.MoveTo(newPathName)

    End Sub

    Private Function fnStringRemove(ByVal strName As String, _
     ByRef intStringStart As Integer, _
      ByRef intRemveStringLen As Integer) As String
        'move the intstringstart one space to left so that it'll be able to remove the enitre string
        intStringStart -= 2
        'get the left side of string up to the start of the string to remove
        'get right side by subtracting the left + lenght of string to remove
        strName = Left(strName, intStringStart) & Right(strName, Len(strName) - (intStringStart + intRemveStringLen + 1))
        Return strName
    End Function


    Private Function STRIP_CLUB_PROTO(ByVal strName As String, _
     ByVal intStorenum As String) As String
        'fix ext for when extensions are not 3 chars.
        Dim ext As String = Right(strName, 4)
        Dim MystrName = Left(strName, Len(strName) - 4)
        If Strings.InStr(MystrName, "136BV") <> 0 Then
            Dim l As Integer = Strings.InStr(MystrName, "136BV")
            MystrName = fnStringRemove(MystrName, l, 5)
            strName = Left(MystrName, l) & intStorenum & Right(MystrName, Len(MystrName) - Len(Left(MystrName, l))) & ext
        End If
        If Strings.InStr(MystrName, "136") <> 0 Then

            Dim l As Integer = Strings.InStr(MystrName, "136")
            MystrName = fnStringRemove(MystrName, l, 3)
            strName = Left(MystrName, l) & intStorenum & Right(MystrName, Len(MystrName) - Len(Left(MystrName, l))) & ext
        End If
        Return strName
    End Function

    Structure SheetFileName
        Public SheetIndex As String
        Public SheetNumber As String
        Public SheetName As String
        Public SheetStoreNumber As String
        Public separator As String
        Public SheetTitle As String
        Public SheetArray() As String
        Function join() As String
            separator = " " & separator & " "
            Return SheetIndex & separator & SheetNumber & " " & SheetName & separator & SheetStoreNumber
        End Function
    End Structure

    Private Function StrEDDSfilenameparser(ByVal StrFilename As FileInfo, _
     Optional ByVal Namestyle As Boolean = True)
        Dim Sheet_Name_Structure As New SheetFileName
        Sheet_Name_Structure.separator = "-"
        'check to see if -Model is on the end of the filename
        If InStr(StrFilename.Name, "-Model", CompareMethod.Text) > 0 Then _
         Exit Function
        Sheet_Name_Structure.SheetName = Right(StrFilename.Name, _
         Len(StrFilename.Extension + 1))
        'tokenize the string into an array of all of its parts
        Sheet_Name_Structure.SheetArray = Split( _
         Sheet_Name_Structure.SheetName, " ", -1, CompareMethod.Text)
        'get the store number.  it should be the last entry in the array. 
        ' except when the names look like
        'sheet-####  for this case i need to run the string backwards and test 
        'each character to see if it is an integer
        Dim reversedStrEntry As String = StrReverse( _
         Sheet_Name_Structure.SheetArray( _
          Sheet_Name_Structure.SheetArray.GetUpperBound( _
           Sheet_Name_Structure.SheetArray.Rank)))
        'test for integers
        Dim i As Boolean = True
        Dim StrChar As String = Nothing
        Dim index As Integer = 1
        Do While i = True
            StrChar = Strings.GetChar(reversedStrEntry, index)
            If IsNumeric(StrChar) = True Then
                Sheet_Name_Structure.SheetStoreNumber.Insert( _
                 Sheet_Name_Structure.SheetStoreNumber.Length(), StrChar)
            Else
                i = False
            End If
            index += 1
        Loop
        Sheet_Name_Structure.SheetStoreNumber = StrReverse( _
            Sheet_Name_Structure.SheetStoreNumber)
        'reset i and index and StrChar
        i = True
        StrChar = Nothing
        index = 1
        'i'm just going to reuse reversedStrEntry
        'this code needs to be refactored becuase its repetitive.
        reversedStrEntry = Sheet_Name_Structure.SheetArray(0)
        Do While i = True
            StrChar = Strings.GetChar(reversedStrEntry, index)
            If IsNumeric(StrChar) = True Then
                Sheet_Name_Structure.SheetIndex.Insert( _
                 Sheet_Name_Structure.SheetIndex.Length(), StrChar)
            Else
                i = False
            End If
            index += 1
        Loop
        'Now to remove the first and last elements of the array since
        'I've just parsed them and don't need them anymore
        Array.Copy(Sheet_Name_Structure.SheetArray, 1, _
                    Sheet_Name_Structure.SheetArray, 0, _
                     Sheet_Name_Structure.SheetArray.Length - 2)
        'now to remove instances where the "-" occurs.  this should only
        'happen for the new style names and shouldn't affect sheet 
        'numbers ie. "A2-2" or "S5-1" since the delimiter is a " " char.
        'return an array that does not include "-"
        Sheet_Name_Structure.SheetArray = Array.FindAll(Sheet_Name_Structure.SheetArray, AddressOf IsStringNotHyphen)
        'sheet numbers are in the form [letter][number]optional{-number} or sometimes {.number}


        Return Sheet_Name_Structure
    End Function

    Private Function IsFilledWithZero(ByVal MyString As String) As Boolean
        'test if MyString has 0 in it
        If MyString = 0 Then
            Return False
        Else
            Return True
        End If
    End Function

    Private Function IsStringNotHyphen(ByVal Mystring As String) As Boolean
        'test if the string is a hyphen
        If Mystring <> "-" Then
            Return True
        Else
            Return False
        End If
    End Function

    'the string version of the parser

    Function StrEDDSfilenameparser(ByVal StrFilename As String, _
     Optional ByVal Namestyle As Boolean = True)
        Dim Sheet_Name_Structure As New SheetFileName
        Sheet_Name_Structure.separator = "-"
        'check to see if -Model is on the end of the filename
        If InStr(StrFilename, "-Model", CompareMethod.Text) > 0 Then _
         Return Nothing
        'remove the extension - only works for 3 character extensions
        'revise this to remove everything after the last "."
        Sheet_Name_Structure.SheetName = Left(StrFilename, _
         Len(StrFilename) - 4)
        'tokenize the string into an array of all of its parts
        Sheet_Name_Structure.SheetArray = Split( _
         Sheet_Name_Structure.SheetName, " ", -1, CompareMethod.Text)
        'get the store number.  it should be the last entry in the array. 
        ' except when the names look like
        'sheet-####  for this case i need to run the string backwards and test 
        'each character to see if it is an integer
        Dim reversedStrEntry As String = StrReverse( _
         Sheet_Name_Structure.SheetArray( _
          Sheet_Name_Structure.SheetArray.Length - 1))
        'test for integers
        Dim i As Boolean = True
        Dim StrChar As String = Nothing
        Dim index As Integer = 1
        If IsNumeric(reversedStrEntry) <> True Then
            Do While index <= Len(reversedStrEntry) And i = True
                StrChar = Strings.GetChar(reversedStrEntry, index)
                If IsNumeric(StrChar) = True Then
                    Sheet_Name_Structure.SheetStoreNumber = _
                     String.Concat(Sheet_Name_Structure.SheetStoreNumber, StrChar)
                Else
                    i = False
                End If
                index += 1
            Loop
            Sheet_Name_Structure.SheetStoreNumber = StrReverse( _
                Sheet_Name_Structure.SheetStoreNumber)
            Sheet_Name_Structure.SheetArray(Sheet_Name_Structure.SheetArray.Length - 1) = Strings.Left( _
                reversedStrEntry, Strings.InStr(reversedStrEntry, Sheet_Name_Structure.SheetStoreNumber))
        Else
            Sheet_Name_Structure.SheetStoreNumber = StrReverse( _
                reversedStrEntry)
            'remove the last element here since it was the actual store number
            Sheet_Name_Structure.SheetArray = ArrayMove(Sheet_Name_Structure.SheetArray, 0, _
                    Sheet_Name_Structure.SheetArray, 0, _
                     Sheet_Name_Structure.SheetArray.Length - 2)
        End If
        'reset i and index and StrChar
        i = True
        StrChar = Nothing
        index = 1
        'i'm just going to reuse reversedStrEntry
        'this code needs to be refactored becuase its repetitive.
        reversedStrEntry = Sheet_Name_Structure.SheetArray(0)
        Do While index <= Len(reversedStrEntry) And i = True
            StrChar = Strings.GetChar(reversedStrEntry, index)
            If IsNumeric(StrChar) = True Then
                Sheet_Name_Structure.SheetIndex = _
                String.Concat(Sheet_Name_Structure.SheetIndex, StrChar)
            Else
                i = False
            End If
            index += 1
        Loop
        'Now to remove the first element of the array since
        'I've just parsed them and don't need them anymore
        Sheet_Name_Structure.SheetArray = ArrayMove(Sheet_Name_Structure.SheetArray, 1, _
                    Sheet_Name_Structure.SheetArray, 0, _
                     Sheet_Name_Structure.SheetArray.Length - 1)
        'test for zero length arrays
        If Sheet_Name_Structure.SheetArray.Length > 0 Then
            'now to remove instances where the "-" occurs.  this should only
            'happen for the new style names and shouldn't affect sheet 
            'numbers ie. "A2-2" or "S5-1" since the delimiter is a " " char.
            'return an array that does not include "-"
            Sheet_Name_Structure.SheetArray = Array.FindAll(Sheet_Name_Structure.SheetArray, AddressOf IsStringNotHyphen)
            'sheet numbers are in the form [letter][number]optional{-number} or sometimes {.number}
            'now that the string array Sheet_Name_Structure.SheetArray is clean we can assume that the sheet
            'number is the first element
            Sheet_Name_Structure.SheetNumber = Sheet_Name_Structure.SheetArray(0)
            'the last element now is either a part of the sheet name or it looks like [part of sheet name]-[sheet number]
            'lets fix it by searching it for the delimiter "-" 
            'if it isn't there then its a safe bet to say we've got a good string
            'using reversedStrEntry again...
            reversedStrEntry = Sheet_Name_Structure.SheetArray(Sheet_Name_Structure.SheetArray.Length - 1)
            index = Strings.InStr(reversedStrEntry, "-", CompareMethod.Text)
            If index > 0 Then
                Sheet_Name_Structure.SheetArray(Sheet_Name_Structure.SheetArray.Length - 1) = Strings.LSet(reversedStrEntry, index)
            End If
            Sheet_Name_Structure.SheetArray = ArrayMove(Sheet_Name_Structure.SheetArray, 1, Sheet_Name_Structure.SheetArray, 0, Sheet_Name_Structure.SheetArray.Length - 1)
            'the order of the remaining elements is the order of the words in the sheet name
            'now i can combine those into the sheet name
            Sheet_Name_Structure.SheetName = Strings.Join(Sheet_Name_Structure.SheetArray, " ")
            'recombine the parts into a sheet name
            Array.Resize(Sheet_Name_Structure.SheetArray, 4)
            Sheet_Name_Structure.SheetArray(0) = Sheet_Name_Structure.SheetIndex
            Sheet_Name_Structure.SheetArray(1) = Sheet_Name_Structure.SheetNumber
            Sheet_Name_Structure.SheetArray(2) = Sheet_Name_Structure.SheetName
            Sheet_Name_Structure.SheetArray(3) = Sheet_Name_Structure.SheetStoreNumber
            Sheet_Name_Structure.SheetTitle = Sheet_Name_Structure.join()
        Else
            Sheet_Name_Structure.SheetTitle = Sheet_Name_Structure.SheetName
        End If
        Return Sheet_Name_Structure.SheetTitle
    End Function
    Private Function ArrayMove(ByVal sourceArray As System.Array, ByVal sourceStart As Integer, ByRef targetArray As System.Array, _
                                 ByVal targetStart As Integer, ByVal targetrangelength As Integer) As System.Array
        Dim Myarray() As String = sourceArray
        If sourceStart = 0 Then
            Array.Resize(Of String)(targetArray, sourceArray.Length - 1)
        Else
            Array.Resize(Of String)(targetArray, sourceArray.Length - sourceStart)
        End If
        Array.Copy(Myarray, sourceStart, targetArray, targetStart, targetrangelength)
        Return targetArray
    End Function

End Module
